using Godot;
using System;
using CurrentGame.NPC;
using CurrentGame.GUI.PlaceGrid;

namespace CurrentGame.Levels.EndLevel;

public partial class EndLevelMain : Node
{
    [Export]
    public Godot.Collections.Array<ShadeCharacter> ReadyShades { get; set; } = [];

    [Export]
    public Area2D ColorChangeArea { get; set; }
    [Export]
    public Area2D ShowAllArea { get; set; }

    [Export]
    public DialogueConfig Dialogue1 { get; set; }

    [Export]
    public Timer DeltaTimer { get; set; }

    [Export]
    public CameraAreaConfig CameraArea { get; set; }

    private SceneSwitch _sceneSwitch;
    private PlaceModeGrid _placeGrid;
    private CinematicCamera _camera;
    private GamePlayGui _gamePlayGui;
    private SelectBox _selectBox;
    private Player _player;

    private float _savedModulate1, _savedModulate2;

    public override void _Ready()
    {
        var map = GetNode<NodeReferenceMap>(Constants.NodeRefMapPath);
        _sceneSwitch = map.SceneSwitch;
        _sceneSwitch.SceneStart += Signal_SceneStart;
        _placeGrid = map.PlacementModeGrid;
        _player = map.MainPlayer;
        _camera = map.GameCamera;
        _gamePlayGui = map.MainGui;
        _selectBox = map.SelectBox;

        _savedModulate1 = _selectBox.AvailableModulate;
        _savedModulate2 = _selectBox.UnavailableModulate;
        _selectBox.AvailableModulate = 0.0f;
        _selectBox.UnavailableModulate = 0.2f;

        _gamePlayGui.DialogueBoxFinished += Signal_DialogueBoxEnd;
        _camera.SetBackgroundColor(0.14f);

        _player.SetHealthPoint(3);
        _player.DisablePlaceMode();
        _player.PlaceModeAvailable = false;
        _player.AttackEnabled = false;
        _placeGrid.FreePlaceCost = true;
    }

    public override void _ExitTree()
    {
        _gamePlayGui.DialogueBoxFinished -= Signal_DialogueBoxEnd;
        _sceneSwitch.SceneStart -= Signal_SceneStart;
        _placeGrid.ClearAllShade();

        _selectBox.AvailableModulate = _savedModulate1;
        _selectBox.UnavailableModulate = _savedModulate2;
    }

    private void Signal_SceneStart()
    {
        GD.Print("Started End Level");
        foreach (var shade in ReadyShades)
        {
            shade.ActivateFallDetection();
            _placeGrid.AppendReadyShade(shade);
        }
    }

    private void Signal_DialogueBoxEnd()
    {
        Dialogue1.QueueFree();
        _player.PlaceModeAvailable = true;
    }

    private void Signal_ColorChangeAreaEnter(Area2D area)
    {
        _camera.SetBackgroundColor(0.3f);
        ColorChangeArea.QueueFree();
    }

    private void Signal_ShowAllAreaEnter(Area2D area)
    {
        _player.SkipInputCheck();
        ShowAllArea.QueueFree();
        _camera.PushCameraAreaConfig(CameraArea);
        DeltaTimer.WaitTime = 4.0f;
        DeltaTimer.Start();
    }

    private void Signal_TimerTimeout()
    {
        _player.EnableInputCheck();
        _camera.PopCameraAreaConfig();
        CameraArea.QueueFree();
    }
}
